const { HttpException } = require('../core/http-exception')

const catchError =async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    // error 堆栈调用信息
    // error 简化 清晰明了得信息给前端
    // http status Code 2XX, 4XX, 5XX
    // ctx.body = '服务器有点问题，你等一下'
    // message
    // error_code 开发者自定义
    // request_url 当前请求url

    // 已知型错误 params 
    // 未知错误 程序潜在错误
    const isHttpException = error instanceof HttpException
    console.log('isHttpException', isHttpException)
    console.log('golble', global.config)
    if(global.config.environment === 'dev' && !isHttpException) {
      throw error
    }

    if (isHttpException) {
      ctx.body = {
        msg: error.msg,
        error_code: error.errorCode,
        reuqest: `${ctx.method} ${ctx.path}`
      }
      ctx.status = error.code
    } else {
      ctx.body = {
        msg: 'we made a mistake',
        error_code: 999,
        reuqest: `${ctx.method} ${ctx.path}`
      }
      ctx.status = 500
    }
  }
}

module.exports = catchError